<template>
  <div class="model-map" id="mountNode"></div>
  <!-- 模型查看 -->
  <!-- <model-view ref="modelViewRef" /> -->
  <!-- 模型注册 -->
  <!-- <model-register ref="modelRegisterRef" /> -->
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { getModelCategoriesMap } from '@/services/modules/model.js'
import { conversionMindMapData } from '@/utils/func.js'
import G6 from '@antv/g6'
// import { MODEL_MANAGE_CONFIG } from '@/constants'
const { Util } = G6
const modelMapColors = [
  '#5B8FF9',
  '#5AD8A6',
  '#5D7092',
  '#F6BD16',
  '#6F5EF9',
  '#6DC8EC',
  '#D3EEF9',
  '#DECFEA',
  '#FFE0C7',
  '#1E9493',
  '#BBDEDE',
  '#FF99C3',
  '#FFE0ED',
  '#CDDDFD',
  '#CDF3E4',
  '#CED4DE',
  '#FCEBB9',
  '#D3CEFD',
  '#945FB9',
  '#FF9845'
]
// const modelMarketStore = useModelMarketStore()
const modelMapData = ref(null)
// const modelRegisterRef = ref(null)
const modelViewRef = ref(null)

/**
 * 颜色状态
 */
const stateColor = ref('')
/**
 * 模型导图树
 */
let modelMapTree = null

const getModelCategoriesMapData = async (name) => {
  return new Promise(async (resolve) => {
    const res = await getModelCategoriesMap({ modelName: name || '' })
    if (res.code === 200) {
      modelMapData.value = res.data
      conversionMindMapData([modelMapData.value])
      resolve(modelMapData.value)
    }
  })
}

/**
 * 思维导图 数据转换
 * @param data 思维导图数据
 */
const dataTransform = (data) => {
  const changeData = (d, level = 0, color) => {
    const data = { ...d }

    switch (level) {
      case 0:
        data.type = 'dice-mind-map-root'
        break
      case 1:
        data.type = 'dice-mind-map-sub'
        break
      default:
        data.type = 'dice-mind-map-leaf'
        break
    }
    if (d.idOperate) {
      data.type = 'dice-mind-map-four'
    }
    data.hover = false

    if (color) {
      data.color = color
    }

    if (d.children) {
      data.children = d.children.map((child) => changeData(child, level + 1, data.color))
    }

    return data
  }

  return changeData(data, 0, '')
}

/**
 * 初始化思维导图
 */
const initModelMindMap = () => {
  // 一级节点
  G6.registerNode(
    'dice-mind-map-root',
    {
      jsx: (cfg) => {
        const width = Util.getTextSize(cfg.label, 16)[0] + 24
        const stroke = cfg.style.stroke || '#096dd9'

        return `
      <group>
        <rect draggable="true" style={{width: ${width}, height: 42, stroke: ${stroke}, radius: 4}} keyshape>
          <text style={{ fontSize: 16, marginLeft: 12, marginTop: 12 }}>${cfg.label}</text>

        </rect>
      </group>
    `
      },
      getAnchorPoints() {
        return [
          [0, 0.5],
          [1, 0.5]
        ]
      }
    },
    'single-node'
  )
  // 二级节点
  G6.registerNode(
    'dice-mind-map-sub',
    {
      jsx: (cfg) => {
        const width = Util.getTextSize(cfg.label, 14)[0] + 24
        stateColor.value = modelMapColors[Math.floor(Math.random() * modelMapColors.length)]

        return `
      <group>
        <rect draggable="true" style={{width: ${width + 24}, height: 22}} keyshape>
          <text draggable="true" style={{ fontSize: 14, marginLeft: 12, marginTop: 6 }}>${
            cfg.label
          }</text>
        </rect>
        <rect style={{ fill: ${stateColor.value}, width: ${width + 24}, height: 3, x: 0, y: 22 }} />

      </group>
    `
      },
      getAnchorPoints() {
        return [
          [0, 0.965],
          [1, 0.965]
        ]
      }
    },
    'single-node'
  )
  // 三级节点
  G6.registerNode(
    'dice-mind-map-leaf',
    {
      jsx: (cfg) => {
        const width = Util.getTextSize(cfg.label, 12)[0] + 24
        const color = stateColor.value
        return `
      <group>
        <rect draggable="true" style={{width: ${width + 20}, height: 26, fill: 'transparent' }}>
          <text style={{ fontSize: 12, marginLeft: 12, marginTop: 6 }}>${cfg.label}</text>

        </rect>
        <rect style={{ fill: ${color}, width: ${width + 24}, height: 3, x: 0, y: 32 }} />

      </group>
    `
      },
      getAnchorPoints() {
        return [
          [0, 0.965],
          [1, 0.965]
        ]
      }
    },
    'single-node'
  )
  //   <rect draggable="true" style={{width: ${width + 20}, height: 26, fill: 'transparent' }}    >

  // <text style={{ fontSize: 12, marginLeft: 12, marginTop: 6 }}>${cfg.label}</text>

  // <text style={{fontSize: 19, marginLeft: ${
  //   width - 6
  // }, marginTop: -15, stroke: ${color}, fill: '#000', cursor: 'pointer', opacity: ${
  // cfg.hover ? 0.75 : 1
  // },next: 'inline'  }} action="add" id="option">...</text>

  // </rect>
  // 四级节点
  G6.registerNode(
    'dice-mind-map-four',
    {
      jsx: (cfg) => {
        const width = Util.getTextSize(cfg.label, 12)[0] + 24
        const color = stateColor.value
        return `
      <group>
        <rect draggable="true" style={{width: ${width + 20}, height: 26, fill: 'transparent' }}    >

          <text style={{ fontSize: 12, marginLeft: 12, marginTop: 6 }}>${cfg.label}</text>

          <text style={{fontSize: 19, marginLeft: ${
            width - 6
          }, marginTop: -15, stroke: ${color}, fill: '#000', cursor: 'pointer', opacity: ${
          cfg.hover ? 0.75 : 1
        },next: 'inline'  }} action="add" id="option"></text>

        </rect>

        <rect style={{ fill: ${color}, width: ${width + 24}, height: 3, x: 0, y: 32 }} />

      </group>
    `
      },
      getAnchorPoints() {
        return [
          [0, 0.965],
          [1, 0.965]
        ]
      }
    },
    'single-node'
  )

  const container = document.getElementById('mountNode')

  const el = document.createElement('span')
  el.innerHTML = '可用鼠标进行拖动、放大缩小...'

  el.style.position = 'absolute'
  el.style.bottom = '20px'
  el.style.right = '20px'
  el.style.fontSize = '12px' // 设置文字大小
  el.style.color = '#666' // 设置文字颜色
  container.appendChild(el)
  const width = container.clientWidth
  const height = container.clientHeight
  const menu = new G6.Menu({
    offsetX: 6,
    offsetY: -50,
    trigger: 'click',
    itemTypes: ['node'],
    getContent(evt) {
      if (evt.target.get('action') === 'add') {
        const outDiv = document.createElement('div')
        outDiv.style.width = 'auto'
        outDiv.innerHTML = `<div style="background-color:#5aa9f7" class="btn-box">
          <button id="btnView" class="icon1 imgBg1" title="模型查看"></button>
        </div>`
        return outDiv
      }
      // <span></span>
      //     <button id="btnConfig" class="icon1 imgBg2" title="模型配置"></button>
      //     <span></span>
      //     <button id="btnEdit" class="icon1 imgBg3" title="模型编辑"></button>
    },
    shouldBegin: (evt) => {
      if (evt.target.get('action') === 'add') {
        return true
      } else {
        return false
      }
    },
    handleMenuClick: (target, evt) => {
      // 查看
      if (target.id === 'btnView') {
        handleViewClick(evt._cfg.model.typeId)
      }

      // 配置
      if (target.id === 'btnConfig') {
        handleConfigClick()
      }

      // 模型修改
      if (target.id === 'btnEdit') {
        handleRegisterClick()
      }
    }
  })
  modelMapTree = new G6.TreeGraph({
    container: container,
    width,
    height,
    fitView: true,
    plugins: [menu], // 配置 Menu 插件
    fitViewPadding: [0],
    layout: {
      type: 'mindmap',
      direction: 'H',
      getHeight: () => {
        return 16
      },
      getWidth: (node) => {
        return node.level === 0
          ? Util.getTextSize(node.label, 16)[0] + 12
          : Util.getTextSize(node.label, 12)[0]
      },
      getVGap: () => {
        return 10
      },
      getHGap: () => {
        return 60
      }
    },
    defaultEdge: {
      type: 'cubic-horizontal',
      style: {
        lineWidth: 2
      }
    },
    minZoom: 0.5,
    modes: {
      default: [
        {
          type: 'collapse-expand',
          onChange: function onChange(item, collapsed) {
            const data = item.get('model')
            data.collapsed = collapsed
            return true
          }
        },
        'drag-canvas',
        'zoom-canvas'
      ]
    }
  })
  modelMapTree.data(dataTransform(modelMapData.value))
  // 渲染
  modelMapTree.render()
}

/**
 * 模型查看
 */
const handleViewClick = async (id) => {
  // 查看之前 清空上次的模型详情存储数据
  modelMarketStore.batchClearRegisterInfoAction()
  await modelMarketStore.fetchModelTypeTreeAction()
  // 查询模型详情
  modelViewRef.value.handleOpenModelInfo()
  modelMarketStore.fetchModelDetailsAction(id)
}

/**
 * 模型配置
 */
const handleConfigClick = () => {
  // modelOperateType.value = MODEL_MANAGE_CONFIG
}

/**
 * 模型编辑
 */
const handleRegisterClick = () => {
  // modelRegisterRef.value.handleOpenModelRegister()
}

// watch(
//   () => modelMapData.value,
//   () => {
//     modelMapTree.data(dataTransform(modelMapData.value))
//     modelMapTree.render()
//   }
// )
async function handleSearchModelName(name) {
  await getModelCategoriesMapData(name)
  modelMapTree.data(dataTransform(modelMapData.value))
  modelMapTree.render()
}
onMounted(async () => {
  await getModelCategoriesMapData()
  /** 初始化思维导图 */
  initModelMindMap()
})
defineExpose({ handleSearchModelName })
</script>

<style scoped lang="less">
.model-map {
  width: 100%;
  height: 100%;
  cursor: pointer;

  // :deep(.g6-component-contextmenu) {
  //   padding: 0;
  //   .circle-item {
  //     fill: #00ffff;
  //   }
  //   .btn-box {
  //     display: flex;
  //     justify-content: space-between;
  //     align-items: center;
  //     padding: 0 5px;
  //     border-radius: 5px;
  //     width: auto;
  //     height: 40px;
  //   }
  //   span {
  //     display: block;
  //     height: 100%;
  //     border: 0.5px solid #ffffffbe;
  //   }
  //   .icon1 {
  //     width: 60px;
  //     height: 40px;
  //     cursor: pointer;
  //     border: 0px;
  //     background-color: #5aa9f7;
  //   }
  //   .icon1:hover {
  //     background-color: #409eff;
  //   }
  //   .imgBg1 {
  //     background: url('@/assets/img/model/ntShow.png') no-repeat;
  //     background-size: 30px 30px;
  //     background-position: center;
  //   }
  //   .imgBg2 {
  //     background: url('@/assets/img/model/ntConfig.png') no-repeat;
  //     background-size: 20px 20px;
  //     background-position: center;
  //   }
  //   .imgBg3 {
  //     background: url('@/assets/img/model/ntEdit.png') no-repeat;
  //     background-size: 20px 20px;
  //     background-position: center;
  //   }
  // }
}
</style>
